const ipUtil = require("../../utils/hostUtil")
const requestUtil = require("../../utils/requestUtil")
Page({
    data: {
        list: [],
        address: "",
        orderId: "",
        money: "0.00",
        addressId: "",
        type: "",
        totalCount: 0,
        interval: "",
		show: true,
		radio: '1',
		name:'',
		moneys:[],
		disabled:false,
		money1:''
    },
	click:function(){
		this.setData({
			show:false
		})
	},
	cancel:function(){
		this.setData({
			show:true
		})
	},
	onChange:function(event) {
	    this.setData({
	      radio: event.detail,
	    });
	  },
	  onClick:function(e) {
		  let that = this
	      const { index,name } = e.currentTarget.dataset;
		  console.log(index)
		  let money=that.data.money
		  wx.setStorageSync('couponid',index)
	      that.setData({
	        radio: index,
			name:name,
			money1:(money-name).toFixed(2),
	      });
	    },
	onClose:function() {
	    this.setData({ show: false });
	  },
	
	  onSelect:function(event) {
	    console.log(event.detail);
	  },
    onLoad: function (options) {
		var that = this
		wx.request({
			url:`${ipUtil.host}${requestUtil.myRedEnvelope}`,
			method:'POST',
			data:{token:wx.getStorageSync('token')},
			header:requestUtil.header,
			success(res) {
				console.log(res.data.data)
				that.setData({
					moneys:res.data.data
				})
			}
		})
        wx.setNavigationBarTitle({title: '确认订单'})
        // 订单id
        var id = options.id;
        // 类型
        var type = options.type;
        if (type == "buynow") {
            that.setData({
                type: type
            })
        }
        // 请求订单数据
        that.loadPage(id);
    }
    , onShow: function () {

    },
    onHide:function (){
        if (this.data.interval != "") {
            clearInterval(this.data.interval);
        }
    },
    onUnload:function (){
        if (this.data.interval != "") {
            clearInterval(this.data.interval);
        }
    },
    /**
     * 点击选择收货地址
     */
    chooseAddress: function (e) {
        wx.navigateTo({
            url: "/pages/adress/adress?type=anything"
        })
    },
    /**
     * 根据id请求订单数据
     * @param id
     */
    loadPage: function (id) {
        var that = this;
        wx.request({
            url: `${ipUtil.host}${requestUtil.order_detail}`,
            method: "POST",
            data: {orderId: id},
            header: requestUtil.header,
            success(res) {
                if (res.data.code == 0) {
                    var list = res.data.data.orderVoList;
                    var totalCount = 0;
                    list.forEach(item => {
                        totalCount += item.account;
                    })
                    that.setData({
                        address: res.data.data.address,
                        list: list,
                        orderId: res.data.data.orderId,
                        money: res.data.data.money.toFixed(2),
						radio:0,
                        addressId: res.data.data.addressId,
                        totalCount: totalCount
                    })
                }
            }
        })
    },
    /**
     *  发起支付
     */
    orderPay: function (e) {
        var that=this;
		var couponid = that.data.radio
        var orderId = e.currentTarget.dataset.orderid;
        // 如果地址已经修改了
        if (this.data.address == null || this.data.address == "" || this.data.address === undefined) {
            wx.showToast({
                title: "请选择收货地址",
                icon: "none",
                duration: 2000
            })
            return;
        }
        if (this.data.addressId != this.data.address.addressid) {
            wx.request({
                url: `${ipUtil.host}${requestUtil.update_order_address}`,
                data: {orderId: orderId, addressId: this.data.addressId},
                header: requestUtil.header,
                method: "POST",
                success(res) {
                    if (res.data.code != 0) {
                        wx.showToast({
                            title: "修改地址失败",
                            ico: "none",
                            duration: 2000
                        })
                        // 返回 不支付
                        return;
                    }
                }
            })
        }
        wx.request({
            url: `${ipUtil.host}${requestUtil.pay}`,
            data: {orderId: orderId,evaluationId:couponid},
            method: "POST",
            header: requestUtil.header,
            success(res) {
                if (res.data.code == 0) {
                    let data = res.data.data;
                    wx.requestPayment({
                        appId: data.appId,
                        timeStamp: data.timeStamp,
                        nonceStr: data.nonceStr,
                        package: data.package,
                        signType: "MD5",
                        paySign: data.sign,
                        success(res1) {
                            that.data.interval = setInterval(function () {
                                wx.request({
                                    url: `${ipUtil.host}${requestUtil.pay_result}`,
                                    data: {orderId: orderId,evaluationId:couponid},
                                    method: "POST",
                                    header: requestUtil.header,
                                    success(res2) {
                                        if (res2.data.data == 1) {
                                            clearInterval(that.data.interval);
                                            wx.showToast({
                                                title: "付款成功",
                                                icon: "success",
                                                duration: 2000
                                            })
                                            wx.navigateTo({
                                                url: `/pages/order/order-detail?orderId=${orderId}`
                                            })
                                        } else if (res2.data.data == -1) {
                                            clearInterval(that.data.interval);
                                            wx.showToast({
                                                title: "订单已取消",
                                                icon: "success",
                                                duration: 2000
                                            })
                                            wx.navigateTo({
                                                url: `/pages/order/order-detail?orderId=${orderId}`
                                            })
                                        }
                                    }
                                });
                            }, 3000)
                        }, fail(res) {
                            wx.showToast({
                                title: "取消支付",
                                icon: "none",
                                duration: 2000
                            })
                            wx.navigateTo({
                                url: `/pages/order/order-detail?orderId=${orderId}`
                            })
                        }
                    })
                } else {
                    wx.showToast({
                        title: res.data.msg,
                        icon: "none",
                        duration: 2000
                    })
                }
            }
        })
    },
	
    /**
     * 增加购物车中商品数量
     * @param index 当前所在的下标
     * @param id 购物车id
     */
    operateCount: function (e) {
        var that = this;
        var operate = e.currentTarget.dataset.operate;
        operate = parseInt(operate);
        var index = e.currentTarget.dataset.index;
        var data = this.data.list
        var count = data[index].account;
        if (operate == 1) {
            if (count + 1 >= 999) {
                wx.showToast({
                    title: "该商品不能购买更多哦~",
                    icon: "none",
                    duration: 2000
                })
                return;
            }
        } else {
            if (count - 1 <= 0) {
                wx.showToast({
                    title: "该商品不能再减少哦~",
                    icon: "none",
                    duration: 2000
                })
                return;
            }
        }
        wx.request({
            url: `${ipUtil.host}${requestUtil.upd_buy_now}`,
            data: {orderId: this.data.orderId, option: operate},
            method: "POST",
            header: requestUtil.header,
            success(res) {
                if (res.data.code == 0) {
                    var list = that.data.list;
                    var money = 0.00;
                    list[index].account += operate;
                    list.forEach(item => {
                        money += (item.account * item.price)
                    })
                    var totalCount = 0;
                    list.forEach(item => {
                        totalCount += item.account;
                    })
                    that.setData({
                        list: list,
                        money: money.toFixed(2),
                        totalCount: totalCount
                    })
                } else {
                    wx.showToast({
                        title: res.data.msg,
                        icon: "none",
                        duration: 2000
                    })
                }
            }
        })
    },
});